<template>
	<view class="viewfill" @tap="curId=''">
		<u-navbar :isBack="false" :border-bottom="false">
			<view class="u-flex u-row-between u-flex-1 u-p-x-30">
				<view class="">
					<text class="u-font-38 text-bold">聊天</text>
				</view>
				<view>
					<text class="u-font-32" v-if="chat.connectStatus==2">
						<u-loading mode="flower"></u-loading>
						<text class="u-m-l-6">连接中...</text>
					</text>
				</view>
				<view class="plus" :class="{show:plus.show}" @tap="plus.show=!plus.show">
					<view class="icon iconfont icon-increase u-font-50"></view>
					<view class="oper">
						<navigator url="/pages/friend/search" hover-class="none" class="u-p-y-20 u-p-x-30 u-flex">
							<text class="cuIcon-friendadd u-m-r-20 u-font-50 text-bold"></text>
							<text class="u-font-34 text-bold u-m-l-6">添加好友</text>
						</navigator>
						<view class="u-p-y-20 u-p-x-30 u-flex" @tap="scan">
							<text class="cuIcon-scan u-m-r-20 u-font-50 text-bold"></text>
							<text class="u-font-34 text-bold u-m-l-6">扫一扫</text>
						</view>
						<navigator url="/pages/group/create" hover-class="none" class="u-p-y-20 u-p-x-30 u-flex">
							<text class="cuIcon-group u-m-r-20 u-font-50 text-bold"></text>
							<text class="u-font-34 text-bold u-m-l-6">创建群聊</text>
						</navigator>
					</view>
				</view>
			</view>
		</u-navbar>
		 <view class="search-place">
			
		</view>
		<navigator url="/pages/search/search" hover-class="none" class="search-box u-flex u-p-x-30 u-border-bottom" :style="{top:`${navBar}px`}">
			<view class="u-flex bg-gray round u-flex-1 u-p-x-20 u-p-y-12">
				<text class="iconfont icon-sousuo u-font-30 u-m-r-10 text-grey"></text>
				<text class="u-font-28 text-grey">搜索</text>
			</view>
		</navigator> 
		<view class="body">
			<view class="netTip u-flex u-p-x-30 u-p-y-10" v-if="isLogin&&!!tipTxt" @tap="reconnect">
				<text class="iconfont icon-tanhaofill u-font-36 u-m-r-20"></text>
				<text>{{tipTxt}}</text>
			</view>
			<chat-item 
				:index="index"
				v-for="(item, index) in conversations"
				:key="item.id"
				:show="curId==item.id"
				@open="onOpen"
				@toChat="toChat"
				@remove="onRemove(item)"
				@toTop="onToTop(item)"
				@cancelTop="onCancelTop(item)"
				:conversation="item"
			></chat-item>
			<view class="empty" v-if="!conversations||!conversations.length">
				<text class="text-gray u-font-32">欢迎您使用司空密信\n\n点击右上角+添加好友</text>
			</view>
		</view>
		<u-modal
			v-model="ask.show"
			showCancelButton
			:content="ask.content"
			@cancel="reject"
			@confirm="resolve"
		>
		</u-modal>
		<view v-show="false">
			{{unread}}
		</view>
		<real-dialog v-model="realAsk.show"></real-dialog>
		<!-- #ifdef APP-PLUS -->
		<updatepage ref="updatepage"/>
		<!-- #endif -->
	</view>
</template>

<script>
	import {jumpTo,dateDiff,toast,getNetworkType,openAppSetting, delay} from "@/utils/util.js"
	import chatItem from "./item.vue"
	// #ifdef APP-PLUS
	import updatepage from "@/components/updatepage.vue"
	// #endif
	import realDialog from "@/components/dialogs/realname/index.vue"
	import * as sessionAPI from "@/api/session.js"
	import {mapGetters,mapActions} from "vuex"
	import chat from "@/IM/index.js"
	import {connectEnum} from "@/IM/IM.js"
	import { ConversationType } from "@/entity/ConversationType"
	import { scanCode } from "@/utils/file"
	export default {
		components:{
			chatItem,
			realDialog,
			// #ifdef APP-PLUS
			updatepage
			// #endif
		},
		data() {
			return {
				curId:'',
				plus:{
					show:false
				},
				ask:{
					show:false,
					content:''
				},
				bridge:null,
				chat,
				isConnected:true,
				netTip:{
					loading:false
				},
				page:{
					startTime:'',
					pageSize:10,
					loading:false,
					nomore:false
				},
				realAsk:{
					show:false,
				},
			};
		},
		computed:{
			...mapGetters('chat',['conversations','unread','online']),
			...mapGetters('user',['userId','isLogin','isReal']),
			...mapGetters('system',['examine']),
			tipTxt(){
				if(!this.isConnected){
					return '网络不给力，请检查网络设置'
				}
				if(this.chat.connectStatus==connectEnum.offline){
					return '连接已断开，点击重试'
				}
				return''
			}
		},
		filters:{
			dateDiff
		},
		watch:{
			userId:{
				handler(val){
					if(val){
						this.resetConv()
					}
				}
			}
		},
		onShow(){
			this.show()
		},
		onLoad(){
			this.load()
		},
		created() {
			uni.$on('networkChange',this.onNetworkChange)
		},
		beforeDestroy() {
			uni.$off('networkChange',this.onNetworkChange)
		},
		onReady() {
			// #ifdef APP-PLUS
			const upRef = this.$refs.updatepage
			upRef.check().then(({needUp,lastVersion})=>{
				console.log(needUp,lastVersion)
				if(!needUp){
					return
				}
				upRef.upgrade();
				if(lastVersion.updateType==2){
					upRef.upgradeEvent()
				}
			})
			// #endif
		},
		async onPullDownRefresh() {
			try{
				await this.pullDownRefresh()
			}finally{
				uni.stopPullDownRefresh()
			}
		},
		onReachBottom() {
			this.reachBottom()
		},
		onUnload() {
			this.unload()
		},
		methods:{
			
			load(){
				getNetworkType().then(({networkType})=>{
					if(networkType=='none'){
						this.isConnected = false
					}
				})
				uni.$on('im_login_success',this.resetConv)
				if(this.userId){
					this.resetConv()
				}
			},
			unload(){
				uni.$off('im_login_success',this.resetConv)
			},
			show(){
				this.fetchAssets()
			},
			async pullDownRefresh(){
				await this.resetConv()
			},
			pageScroll(e){
				
			},
			reachBottom(){
				const oldLength = this.conversations.length;
				console.log(oldLength)
				this.moreConv().then(()=>{
					const nowLength = this.conversations.length
					if(oldLength==nowLength&&!this.page.nomore){
						this.reachBottom()
					}
				})
			},
			
			...mapActions('chat',['removeConversation','setConversation','loginChat','fetchConversationList']),
			...mapActions('wallet',['fetchAssets']),
			onNetworkChange({isConnected}){
				this.isConnected = isConnected
			},
			async resetConv(){
				if(this.resetConv.lock){
					return
				}
				try{
					this.resetConv.lock = true
					this.page.nomore = false
					this.page.startTime = ''
					await this.moreConv()
				}finally{
					delay(1000).then(()=>{
						this.resetConv.lock = false
					})
				}
			},
			
			async moreConv(){
				if(this.page.loading){
					throw new Error('正在请求中')
				}
				try{
					this.page.loading = true
					if(this.page.nomore){
						return []
					}
					const convs = await this.fetchConversationList(this.page)
					if(!convs||convs.length<this.page.pageSize){
						this.page.nomore = true
					}else{
						const last = convs.slice(-1)[0]
						this.page.startTime = last.lastTime
					}
				}finally{
					this.page.loading = false
				}
			},
			
			async reconnect(){
				if(!this.isConnected){
					return openAppSetting()
				}
				try{
					this.netTip.loading = true
					await this.loginChat()
				}finally{
					this.netTip.loading = false
				}
			},
			resolve(e){
				this.bridge&&this.bridge.resolve&&this.bridge.resolve(e)
			},
			reject(e){
				this.bridge&&this.bridge.reject&&this.bridge.reject(e)
			},
			onOpen(id){
				this.curId = id
			},
			async onRemove(conv){
				try{
					await new Promise((resolve,reject)=>{
						this.bridge = {
							resolve,
							reject
						}
						this.ask.show = true
						this.ask.content = `确认删除会话吗?`
					})
					await sessionAPI.removeSession(conv.id,conv.type == ConversationType.Single?'用户':(conv.type == ConversationType.Group?'群':''))
					this.removeConversation(conv.id)
				}finally{
					this.curId = ''
				}
			},
			async onToTop(conv){
				if(conv.sid){
					await sessionAPI.setTop({id:conv.sid,status:1})
				}
				this.setConversation({
					...conv,
					isTop:true
				})
				this.curId = ''
			},
			async onCancelTop(conv){
				if(conv.sid){
					await sessionAPI.setTop({id:conv.sid,status:0})
				}
				this.setConversation({
					...conv,
					isTop:false
				})
				this.curId = ''
			},
			toChat(item){
				if(this.curId){
					return
				}
				if(item.type==ConversationType.Group){
					jumpTo(`/pages/room/multi?id=${item.id}`)
				}else if(item.type==ConversationType.Single){
					jumpTo(`/pages/room/single?id=${item.id}`)
				}
			},
			async scan(){
				const {result} = await scanCode({scanType:['qrCode']})
				if(/^API:/.test(result)){
					const [fun,pram] =result.slice(4).split('?')
					const pramObj = !!pram?pram.split('&').map(item=>item.split('=')).reduce((r,[k,v])=>{r[k]=v; return r},{}):undefined;
					this[fun]&&this[fun](pramObj)
				}
				if(/^PATH:/.test(result)){ 
					const url = result.slice(5)
					uni.navigateTo({
						url
					})
				}
				if(/^login:qr:/.test(result)){
					const id = result.slice(9)
					uni.navigateTo({
						url:`/pages/login/scan?id=${id}`
					})
				}
			},
			realGuard(){
				if(!this.isReal){
					this.realAsk.show = true
					throw new Error('请完成实名认证')
				}
			},
			realJump(url){
				this.realGuard()
				jumpTo(url)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.viewfill{
		min-height: calc(100vh - 100rpx);
	}
	.notice{
		display: flex;
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
		.avatar{
			flex-shrink: 0;
			position: relative;
		}
		.content{
			flex: 1;
			width: 200rpx;
			margin-left: 24rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-around;
		}
		.msg{
			line-height: 1;
		}
	}
	.plus{
		position: relative;
		.icon{
			transition: all 0.3s ease-out;
		}
		&::before{
			content: '';
			display: block;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 3;
			pointer-events: none;
			transition: all 0.3s ease-out;
		}
		.oper{
			position: absolute;
			bottom: -18rpx;
			right: -8rpx;
			white-space: nowrap;
			padding: 30rpx 40rpx 30rpx 10rpx;
			background-color: #FFFFFF;
			z-index: 4;
			transform: translateY(90%);
			border-radius: 10rpx;
			opacity: 0;
			transition: all 0.3s ease-out;
			pointer-events: none;
			&::before{
				content: '';
				position: absolute;
				top: -18rpx;
				right: 20rpx;
				border-left: 10rpx solid transparent;
				border-right: 10rpx solid transparent;
				border-bottom: 20rpx solid #FFFFFF;
			}
		}
		&.show{
			.icon{
				transform: rotate(45deg);
			}
			&::before{
				background-color: rgba($color: #000000, $alpha: 0.6);
				pointer-events: auto;
			}
			.oper{
				opacity: 1;
				transform: translateY(100%);
				pointer-events: auto;
			}
		}
		
	}
	.netTip{
		background-color: rgba($color:#e54d42, $alpha:0.2);
		color: #e54d42;
		&.green{
			background-color: #39b54a;
			color: #ffffff;
		}
	}
	.empty{
		width: 750rpx;
		height: 750rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.search-place{
		height: 90rpx;
	}
	.search-box{
		position: fixed;
		left: 0;
		right: 0;
		background-color: #ffffff;
		z-index: 100;
		height: 90rpx;
	}
</style>
